#include "styledtreeview.h"
#include <QVBoxLayout>
#include <QHeaderView>
#include <QStandardItem>
#include <QApplication>
#include <QModelIndex>

StyledTreeView::StyledTreeView(QWidget *parent)
    : QWidget(parent)
    , treeView(new QTreeView(this))
    , model(new QStandardItemModel(this))
    , mainLayout(new QVBoxLayout(this))
{
    setupUI();
}

void StyledTreeView::setupUI()
{
    treeView->setModel(model);

    // 基本设置
    treeView->setHeaderHidden(false);
    treeView->setSelectionMode(QAbstractItemView::SingleSelection);
    treeView->setSelectionBehavior(QAbstractItemView::SelectRows);

    // 连接点击信号
    connect(treeView, &QTreeView::clicked, this, &StyledTreeView::onTreeViewClicked);

    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);
    mainLayout->addWidget(treeView);
    this->setLayout(mainLayout);

    applyTreeStyling();
}

void StyledTreeView::applyTreeStyling()
{
    treeView->header()->setStyleSheet(
        "QHeaderView::section {"
        "   font-weight: bold;"
        "   padding: 4px;"
        "}"
    );

    treeView->setStyleSheet(QString());
    treeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents);

    int minWidthPerColumn = 100;
    int minTotalWidth = model->columnCount() * minWidthPerColumn;
    if (minTotalWidth < 200) {
        minTotalWidth = 200;
    }
    treeView->setMinimumWidth(minTotalWidth);
}

void StyledTreeView::setHeaderLabels(const QStringList& labels)
{
    model->setColumnCount(labels.size());
    for (int i = 0; i < labels.size(); ++i) {
        model->setHeaderData(i, Qt::Horizontal, labels.at(i));
    }
    applyTreeStyling();
}

void StyledTreeView::setTreeData(const QList<QMap<QString, QString>>& data)
{
    treeData = data; // 保存原始数据
    model->removeRows(0, model->rowCount());
    populateTree(data);
    treeView->expandAll();
}

void StyledTreeView::populateTree(const QList<QMap<QString, QString>>& data)
{
    QMap<QString, QStandardItem*> itemMap;

    // 创建根节点
    for (const auto &itemData : data) {
        QString parentId = itemData.value("parentId", "");
        if (parentId.isEmpty() || parentId == "0") {
            QList<QStandardItem*> rowItems;
            for (int col = 0; col < model->columnCount(); ++col) {
                QVariant headerData = model->headerData(col, Qt::Horizontal);
                QString key = headerData.toString();
                QString value = itemData.value(key, "");
                QStandardItem *item = new QStandardItem(value);
                item->setEditable(false);
                rowItems.append(item);
            }
            if (!rowItems.isEmpty()) {
                model->appendRow(rowItems);
                QString id = itemData.value("id", "");
                if (!id.isEmpty()) {
                    itemMap[id] = rowItems.first();
                }
            }
        }
    }

    // 创建子节点
    for (const auto &itemData : data) {
        QString parentId = itemData.value("parentId", "");
        if (!parentId.isEmpty() && parentId != "0" && itemMap.contains(parentId)) {
            QStandardItem *parentItem = itemMap[parentId];
            QList<QStandardItem*> rowItems;
            for (int col = 0; col < model->columnCount(); ++col) {
                QVariant headerData = model->headerData(col, Qt::Horizontal);
                QString key = headerData.toString();
                QString value = itemData.value(key, "");
                QStandardItem *item = new QStandardItem(value);
                item->setEditable(false);
                rowItems.append(item);
            }
            if (!rowItems.isEmpty()) {
                parentItem->appendRow(rowItems);
                QString id = itemData.value("id", "");
                if (!id.isEmpty()) {
                    itemMap[id] = rowItems.first();
                }
            }
        }
    }
}

// 处理树形视图点击事件
void StyledTreeView::onTreeViewClicked(const QModelIndex& index)
{
    if (!index.isValid()) return;

    // 获取点击行的第一个单元格（通常包含标识信息）
    QModelIndex idIndex = index.siblingAtColumn(0);
    if (!idIndex.isValid()) return;

    // 查找对应的原始数据
    QString nodeText = idIndex.data().toString();
    for (const auto& nodeData : treeData) {
        if (nodeData.value("name") == nodeText) {
            QString nodeId = nodeData.value("id");
            emit nodeClicked(nodeId, nodeData); // 发射信号
            break;
        }
    }
}

// 获取选中节点的数据
QMap<QString, QString> StyledTreeView::getSelectedNodeData() const
{
    QModelIndexList selection = treeView->selectionModel()->selectedIndexes();
    if (selection.isEmpty()) return QMap<QString, QString>();

    QString nodeText = selection.first().data().toString();
    for (const auto& nodeData : treeData) {
        if (nodeData.value("name") == nodeText) {
            return nodeData;
        }
    }
    return QMap<QString, QString>();
}
